﻿// Decompiled with JetBrains decompiler
// Type: Appkiz.Base.Services.Http.AccountAllAndroid
// Assembly: Appkiz.Base, Version=2.79.4.0, Culture=neutral, PublicKeyToken=null
// MVID: C664EDF1-430B-4269-80E2-26AD6B0F4DA6
// Assembly location: D:\i8Office2\Web\bin\Appkiz.Base.dll

using Appkiz.Library.Common;
using Appkiz.Library.Security;
using Appkiz.Library.Security.Authentication;
using Microsoft.International.Converters.PinYinConverter;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Tiger.Common;

namespace Tiger.Controllers
{
    public class PeopleController : Controller
    {
        private string[] pinyinKeys = new string[2]
        {
            "XI4",
            "JIA3"
        };
        private string indexChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private string unknownStr = "*";

        #region 获得系统通讯录
        public void ProcessRequest()
        {
            HttpContext context = System.Web.HttpContext.Current;

            try
            {
                //OrgMgr orgMgr = new OrgMgr();
                //context.Response.ContentType = "text/plain";
                if (string.IsNullOrEmpty(context.User.Identity.Name))
                {
                    context.Response.Write(JsonConvert.SerializeObject((object)new
                    {
                        Succeed = false,
                        Message = "SESSION_INVALID"
                    }));
                    context.Response.End();
                }
                //else
                //{
                //    List<object> objectList = new List<object>();
                //    Dictionary<string, List<object>> dictionary = new Dictionary<string, List<object>>();

                //    List<Employee> employee1 = orgMgr.FindEmployee("EmplEnabled=1", (Hashtable)null, "EmplName", 1, 99999);
                //    foreach (Employee employee2 in employee1)
                //    {
                //        User userByEmplId = orgMgr.GetUserByEmplID(employee2.EmplID);
                //        string key = this.pinyin(employee2.EmplName);
                //        if (!this.indexChar.Contains(key))
                //            key = this.unknownStr;
                //        if (dictionary.Keys.Contains<string>(key))
                //            dictionary[key].Add((object)new
                //            {
                //                ID = employee2.EmplID,
                //                Name = employee2.EmplName,
                //                DeptID = employee2.DeptID,
                //                DeptName = employee2.DeptName,
                //                DeptAndPosStr = employee2.DeptAndPosStr,
                //                LoginName = (userByEmplId != null ? userByEmplId.UserName : "")
                //            });
                //        else
                //            dictionary.Add(key, new List<object>()
                //            {
                //              (object) new
                //              {
                //                ID = employee2.EmplID,
                //                Name = employee2.EmplName,
                //                DeptID = employee2.DeptID,
                //                DeptName = employee2.DeptName,
                //                DeptAndPosStr = employee2.DeptAndPosStr,
                //                LoginName = (userByEmplId != null ? userByEmplId.UserName : "")
                //              }
                //            });
                //    }
                //context.Response.Write(JsonConvert.SerializeObject((object)new
                //{
                //    Succeed = true,
                //    Data = dictionary,
                //    Count = employee1.Count
                //}));
                //}
                else
                {
                    using (StreamReader sr = new StreamReader(Server.MapPath("~/contact.txt")))
                    {
                        context.Response.Write(sr.ReadToEnd());
                    }
                }
            }
            catch (Exception ex)
            {
                LogService.WriteLog("Tiger", "Message:" + string.Format("Msg:{0}", ex.Message), "ProcessRequest", LogService.LogLevel.Debug);

                context.Response.Write(JsonConvert.SerializeObject((object)new
                {
                    Succeed = false,
                    Message = ex.Message
                }));
            }
        }
        #endregion

        #region 根据手机号/座机号/短号搜索
        /// <summary>
        /// 根据手机号/座机搜索
        /// </summary>
        /// <returns></returns>
        public ActionResult SearchPeople()
        {
            /*
             * 变量定义
             */
            // 返回数据结果集
            List<object> ResultList = new List<object>();
            // 账号管理
            OrgMgr orgMgr = new OrgMgr();

            /*
             * 参数获取
             */
            // 手机号/座机
            var Contact = Request.Params["contact"];


            /*
             * 参数校验
             */
            // 手机号/座机
            if (string.IsNullOrEmpty(Contact))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "手机号/座机号不能为空"
                });
            }
            // 格式校验
            Regex regex = new Regex(@"^\d+$");
            if (!regex.IsMatch(Contact))
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = "手机号/座机号格式不正确"
                });
            }

            /*
             * 搜索符合条件的联系人
             */
            var sql = @"SELECT
                            DISTINCT EmplID
                        FROM
                            ORG_EmployeeContactInfo
                        WHERE
                            ORG_EmployeeContactInfo.ContactInfoTypeID in ('tel', 'mobile')
                        AND
                            ORG_EmployeeContactInfo.ContactInfoValue like '%{0}%'
                        GROUP BY
                            EmplID";
            var EmplIDList = DbUtil.ExcuteSqlCommand(string.Format(sql, Contact), DbUtil.People_EmplListHandler);

            foreach (var EmplID in EmplIDList)
            {
                Employee employee = orgMgr.GetEmployee(EmplID.ToString());

                if (employee != null)
                {
                    User userByEmplId = orgMgr.GetUserByEmplID(employee.EmplID);

                    ResultList.Add(new
                    {
                        ID = employee.EmplID,
                        Name = employee.EmplName,
                        DeptID = employee.DeptID,
                        DeptName = employee.DeptName,
                        DeptAndPosStr = employee.DeptAndPosStr,
                        LoginName = (userByEmplId != null ? userByEmplId.UserName : "")
                    });
                }
            }

            return new JsonNetResult(new
            {
                Succeed = true,
                Data = ResultList,
                Count = ResultList.Count
            });
        }


        #endregion

        #region 更新缓存中的手机号
        public ActionResult SyncContactCache()
        {
            try
            {
                OrgMgr orgMgr = new OrgMgr();

                var employee = (User.Identity as AppkizIdentity).Employee;
                List<object> objectList = new List<object>();
                Dictionary<string, List<object>> dictionary = new Dictionary<string, List<object>>();

                List<Employee> employee1 = orgMgr.FindEmployee("EmplEnabled=1", (Hashtable)null, "EmplName", 1, 99999);
                foreach (Employee employee2 in employee1)
                {
                    User userByEmplId = orgMgr.GetUserByEmplID(employee2.EmplID);
                    string key = this.pinyin(employee2.EmplName);
                    if (!this.indexChar.Contains(key))
                        key = this.unknownStr;
                    if (dictionary.Keys.Contains<string>(key))
                        dictionary[key].Add((object)new
                        {
                            ID = employee2.EmplID,
                            Name = employee2.EmplName,
                            DeptID = employee2.DeptID,
                            DeptName = employee2.DeptName,
                            DeptAndPosStr = employee2.DeptAndPosStr,
                            LoginName = (userByEmplId != null ? userByEmplId.UserName : "")
                        });
                    else
                        dictionary.Add(key, new List<object>()
                            {
                              (object) new
                              {
                                ID = employee2.EmplID,
                                Name = employee2.EmplName,
                                DeptID = employee2.DeptID,
                                DeptName = employee2.DeptName,
                                DeptAndPosStr = employee2.DeptAndPosStr,
                                LoginName = (userByEmplId != null ? userByEmplId.UserName : "")
                              }
                            });
                }

                // 写入文件
                using(StreamWriter sw = new StreamWriter(Server.MapPath("~/contact.txt")))
                {
                    sw.Write(JsonConvert.SerializeObject((object)new
                    {
                        Succeed = true,
                        Data = dictionary,
                        Count = employee1.Count
                    }));
                }

                return new JsonNetResult(new
                {
                    Succeed = true,
                    Message = "更新通讯录缓存成功"
                });
            }
            catch (Exception e)
            {
                return new JsonNetResult(new
                {
                    Succeed = false,
                    Message = e.Message
                });
            }
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public string pinyin(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
                return (string)null;
            try
            {
                if (!ChineseChar.IsValidChar(str[0]))
                    return str[0].ToString().ToUpper();
                ChineseChar chineseChar = new ChineseChar(str[0]);
                if (chineseChar.Pinyins.Count > 1 && chineseChar.IsPolyphone)
                {
                    foreach (string pinyinKey in this.pinyinKeys)
                    {
                        if (chineseChar.HasSound(pinyinKey))
                            return pinyinKey[0].ToString().ToUpper();
                    }
                }
                return chineseChar.Pinyins.FirstOrDefault<string>().ToString()[0].ToString().ToUpper();
            }
            catch
            {
                return str[0].ToString().ToUpper();
            }
        }
    }
}
